package com.nantian.logic.controller.mainControl.activityControl;

import com.cuit.springboot.gdao.activity.ActivityMapper;
import com.cuit.springboot.gdao.activity.ApplyActivityMapper;
import com.cuit.springboot.gdao.common.ArticleHtmlMapper;
import com.cuit.springboot.gdao.user.StudentMapper;
import com.cuit.springboot.gentry.activity.Activity;
import com.cuit.springboot.gentry.activity.ApplyActivity;
import com.cuit.springboot.gentry.common.ArticleHtml;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nantian.logic.utils.*;
import com.nantian.model.security.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/activity")
public class ActivityController {
    private final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    ActivityMapper activityMapper;
    @Autowired
    ArticleHtmlMapper articleHtmlMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    ApplyActivityMapper applyActivityMapper;
    @Autowired
    TokenUtil tokenUtil;

    /**
     * “活动信息修改”接口，包括：“审核状态修改”
     * 需要参数：所修改的活动内容，需含活动id（actId）
     */
    @PostMapping(value = "/update")
    public UniversalResult<Object> update(@RequestBody Map map) {
        activityMapper.updateConfirm(map);
        return new UniversalResult<>(UniversalResult.SUCCESS, "更新成功");
    }


    /**
     * “待审核活动列表”获取接口
     * 需要参数：分页参数
     */
    @PostMapping(value = "/select")
    public UniversalResult select(@RequestBody Map map) {
        List<Activity> AList = activityMapper.selectByConfirm();
        if (AList.size() == 0) {
            return new UniversalResult(UniversalResult.GETNULL, "没有待审核活动");
        } else
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", AList);
    }


    /**
     * “发布活动”接口
     * 需要参数：活动实体
     */
    @PostMapping(value = "/publish")
    public UniversalResult publish(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String userId = tokenUtil.getUserId(request);
        //获取当前用户角色
        User user = tokenUtil.getUserInfo(request);
        ArticleHtml articleHtml = new ArticleHtml();
        Activity activity = setActivity(map);
        //管理员发布官方活动
        if (user.getRoletype().contains("A")) {
            articleHtml.setType(Byte.valueOf("0"));
            activity.setActType("1");
        }
        //学生发布活动
        else {
            List<Map> campus = studentMapper.selectCampusByUserId(userId);
            articleHtml.setType(Byte.valueOf("2"));
            activity.setActType("0");
            if (campus.size() == 1) {
                activity.setCampId((Integer) campus.get(0).get("campusid"));
            }
            else if (campus.size()>1){
                return new UniversalResult(UniversalResult.FAILURE, "您加入了多个社团，请联系管理员");
            }
            else {
                return new UniversalResult(UniversalResult.FAILURE, "请先加入一个社团");
            }
        }
        //学生所在社团
        articleHtml.setContent(map.get("actDetail"));
        articleHtml.setArticleId(uuidGenerate.generate());
        articleHtml.setUploadtime(DateUtils.getDateTime());
        articleHtml.setDel(Byte.valueOf("0"));
        articleHtml.setEnabled(Byte.valueOf("0"));
        articleHtml.setUserid(userId);
        articleHtmlMapper.insert(articleHtml);
        activity.setActDetailId(articleHtml.getArticleId());
        activity.setActBelong(userId);
        activityMapper.insert(activity);
        return new UniversalResult(UniversalResult.SUCCESS, "活动已发布");
    }

    private Activity setActivity(Map<String, String> map) {
        Activity activity = new Activity();
        activity.setActBegDate(map.get("actBegDate") == null ? "null" : map.get("actBegDate"));
        activity.setActConfirm((byte) 0);
        activity.setActEndDate(map.get("actEndDate") == null ? "null" : map.get("actEndDate"));
        activity.setActFeedback(map.get("actFeedback") == null ? "null" : map.get("actFeedback"));
        activity.setActMater(map.get("actMater") == null ? "null" : map.get("actMater"));
        activity.setActMoney(map.get("actMoney") == null ? "null" : map.get("actMoney"));
        activity.setActName(map.get("actName") == null ? "null" : map.get("actName"));
        activity.setActNum(map.get("actNum") == null ? "null" : map.get("actNum"));
        activity.setActPlace(map.get("actPlace") == null ? "null" : map.get("actPlace"));
        activity.setActPropaWay(map.get("actPropaWay") == null ? "null" : map.get("actPropaWay"));
        activity.setActProportion(Integer.valueOf((map.get("actProportion") == null || "".equals(map.get("actProportion"))) ? "80" : map.get("actProportion")));
//        activity.setActType(map.get("actType") == null ? "null" : map.get("actMoney"));
        return activity;
    }

    /**
     * “活动详情”查询接口
     * 需要参数：活动id（actId）
     */
    @PostMapping(value = "selectInfo")
    public UniversalResult<Map<String, Object>> selectInfo(@RequestBody Map<String, Integer> map) {
        int actId = map.get("actId");
        if (StringUtils.isBlank(String.valueOf(actId)))
            return new UniversalResult<>(UniversalResult.GETNULL, "活动id不能为空");
        Map<String, Object> activity = activityMapper.selectActInfo(actId);
        if (activity != null) {
            Map<String, Object> article = new HashMap<>();
            Map<String, Object> student = new HashMap<>();
            MapUtils.moveMapValue(activity, article, "articleId");
            MapUtils.moveMapValue(activity, article, "uploadTime");
            MapUtils.moveMapValue(activity, article, "articleType");
            MapUtils.moveMapValue(activity, article, "articleEnabled");
            MapUtils.moveMapValue(activity, article, "content");
            activity.put("article", article);
            MapUtils.moveMapValue(activity, student, "userId");
            MapUtils.moveMapValue(activity, student, "username");
            MapUtils.moveMapValue(activity, student, "sex");
            MapUtils.moveMapValue(activity, student, "qq");
            MapUtils.moveMapValue(activity, student, "phone");
            MapUtils.moveMapValue(activity, student, "entrance");
            MapUtils.moveMapValue(activity, student, "majorSub");
            MapUtils.moveMapValue(activity, student, "campusId");
            MapUtils.moveMapValue(activity, student, "universityId");
            MapUtils.moveMapValue(activity, student, "areaId");
            MapUtils.moveMapValue(activity, student, "department");
            MapUtils.moveMapValue(activity, student, "positionId");
            MapUtils.moveMapValue(activity, student, "special");
            MapUtils.moveMapValue(activity, student, "authForView");
            MapUtils.moveMapValue(activity, student, "campusName");
            activity.put("student", student);
            activity.put("applicant", applyActivityMapper.selectByActId(actId));
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", activity);
        } else
            return new UniversalResult<>(UniversalResult.GETNULL, "您要查询的活动不见啦");
    }

    /**
     * “活动列表”获取接口
     * 需要参数：分页参数(pageNo和pageSize)
     * 分页查询参考此处
     */
    @PostMapping(value = "selectList")
    public UniversalResult<PageInfo<Activity>> selectList(@RequestBody Map<String, Integer> map) {
        if (MapUtils.checkPageIsNull(map))
            return new UniversalResult<>(UniversalResult.GETNULL, "分页参数不能为空");
        else {
            PageHelper.startPage(map.get("pageNo"), map.get("pageSize"));
            PageInfo<Activity> page = new PageInfo<>(activityMapper.selectAll());
            if (page.getList().size() > 0)
                return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", page);
            else
                return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
        }
    }

    /**
     * 根据sId查询其全部活动
     * 所需参数:分页参数和sId
     */
    @PostMapping(value = "selectWhoseList")
    public UniversalResult<PageInfo<Map<String, Object>>> selectWhoseList(@RequestBody Map<String, Object> map) {
        if (MapUtils.checkKeyIsNull(map, "pageNo", "pageSize", "sId"))
            return new UniversalResult<>(UniversalResult.GETNULL, "参数不能为空");
        else {
            PageHelper.startPage((int)map.get("pageNo"), (int)map.get("pageSize"));
            PageInfo<Map<String,Object>> page = new PageInfo<>(activityMapper.selectWhoseList(map.get("sId").toString()));
            if (page.getList().size() > 0)
                return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", page);
            else
                return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
        }
    }

    /**
     * “申请活动”接口
     * 需要参数：申请者id（bId）、活动id（actId）
     */
    @PostMapping(value = "/applyAct")
    public UniversalResult<Object> applySup(@RequestBody ApplyActivity AA, HttpServletRequest request) {
        String bId = tokenUtil.getUserId(request);
        if (StringUtils.isBlank(bId))
            return new UniversalResult<>(UniversalResult.UNLOGIN, "登录信息失效，请重新登陆");
        if (applyActivityMapper.selectMapBy(MapUtils.setSelectStatement("id", "BId=" + bId + " AND act_id=" + AA.getActId())) != null)
            return new UniversalResult<>(UniversalResult.FAILURE, "您已经申请过该赞助了");
        Activity act = activityMapper.selectByPrimaryKey(AA.getActId());
        if (act != null) {
            AA.setBid(bId);
            AA.setStatus((byte) 0);
            AA.setDate(DateUtils.getDateTime());
            AA.setDel((byte) 0);
            applyActivityMapper.insert(AA);
            return new UniversalResult<>(UniversalResult.SUCCESS, "申请成功");
        } else
            return new UniversalResult<>(UniversalResult.GETNULL, "您要申请的活动不见啦");
    }

    /**
     * “我的赞助申请”查询接口
     * 需要参数：查询者id（sId）
     */
    @PostMapping(value = "myApply")
    public UniversalResult<List<ApplyActivity>> myApply(HttpServletRequest request) {
        String bId = tokenUtil.getUserId(request);
        if (StringUtils.isBlank(bId))
            return new UniversalResult<>(UniversalResult.UNLOGIN, "登录信息失效，请重新登陆");
        List<ApplyActivity> applyList = applyActivityMapper.selectMyApplyActInfo(bId);
        if (applyList.size() == 0)
            return new UniversalResult<>(UniversalResult.GETNULL, "空空如也");
        else
            return new UniversalResult<>(UniversalResult.SUCCESS, "查询成功", applyList);
    }
}
